// 设置保存路径和文件名
const multer = require("multer");
const {join, extname, basename} = require("path");
const writeLogs = require('./writeLogs')

const storage = multer.diskStorage({
    destination: function(req, res, cb) {
        // 设置文件存储路径
        const dir = req.auth ?
            join(__dirname, '../', '../', 'pics', req.auth.username) :
            join(__dirname, '../', '../', 'pics', 'public')
        cb(null, dir)
    },
    filename: function(req, file, cb) {
        // 设置文件名， 该操作可以解码中文字符防止乱码
        file.originalname = Buffer.from(file.originalname, 'latin1').toString('utf8')
        const ext = extname(file.originalname);
        cb(null, basename(file.originalname, ext) + "-" + Date.now() + ext)
    }
})

const filter = function (req, file, cb) {
    const reg = /^image/;
    if (reg.test(file.mimetype)) cb(null, true);
    else cb(null, false);
}

const limits = {
    fieldSize: '10MB',
}

exports.uploadModule = multer({
    storage: storage,
    fileFilter: filter,
    limits: limits,
})

exports.uploadHandler = (req, res) => {
    const username = req.auth ? req.auth.username : '游客';
    writeLogs('upload', {
        username,
        filename: req.file.originalname
    })
    res.cc('ok',0)
}